package com.itheima.health.job;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.health.service.OrderSettingService;
import com.itheima.health.utils.aliyunoss.AliyunUtils;
import com.itheima.health.utils.date.DateUtils;
import com.itheima.health.utils.resources.RedisConstant;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;


    @JobHandler(value = "heima.setmeal.clean.img.job") //  web配置JobHandler的名称
    @Component
    public class CleanSetmealImageJob extends IJobHandler {

        @Autowired
        private RedisTemplate redisTemplate;

        @Reference
        private OrderSettingService orderSettingService;


        /**
         * 但是spring的@Scheduled只支持6位，年份是不支持的，带年份的7位格式会报错：
         * Cron expression must consist of 6 fields (found 7 in "1/5 * * * * ? 2018")
         * 通过cron表达式 来配置 该方法的执行周期
         **/

        @Override
        public ReturnT<String> execute(String s) throws Exception {
//      Date currentTime = new Date();
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("is_delete",0);//  有效数据
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
//            String date = "2020-07-30";
            String date = new Date().toString();
//        Integer id =1;
//        Date date = formatter.parse(str);
//        orderSettingService.deleteFile(date);
            orderSettingService.UpdateIsDatelet(date);
            System.out.println("删除成功");


            Set<String> sdiff = redisTemplate.opsForSet().difference(RedisConstant.SETMEAL_PIC_RESOURCES, RedisConstant.SETMEAL_PIC_DB_RESOURCES);
            if(sdiff.size()>0){
                for (String filename : sdiff) {
                    AliyunUtils.deleteFile(filename); //  删除阿里云上的多余图片
                }
                redisTemplate.delete(RedisConstant.SETMEAL_PIC_RESOURCES);  //  删除 redis上的两个集合
                redisTemplate.delete(RedisConstant.SETMEAL_PIC_DB_RESOURCES);
                System.out.println("---阿里云图片删除成功---");
            }else{
                System.out.println("----任务调度执行一次----");
            }
            return SUCCESS;
        }


    }

